<?php
class MemberController extends MController
{
	/**
	 * 登陆
	 */
	public function actionLogin()
	{
		$request = array();
		$params = array('username', 'password');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['username'] || !$request['password']) {
			$this->return_json('用户名或密码不能为空', 1);
		}
		
		if ($this->model('user')->isExistByUserName($request['username'], md5($request['password']))) {
			$this->model('user')->updateLoginTime($request['username']);
			$this->return_json(0, '登陆成功');
		}
		$this->return_json(1, '您输入的用户名或密码错误。');
	}
	
	/**
	 * 注册
	 */
	public function actionRegister()
	{
		$request = array();
		$params = array('username', 'password', 'introrid', 'nickname', 'sex', 'hobby', 'birthday', 'logo');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['username'] || !$request['password']) {
			$this->return_json(1, '用户名或密码不能为空');
		}
		if ($this->model('user')->checkUserName($request['username'])) {
			$this->return_json(1, '用户名已存在');
		}
		
		$photoid = 0;
		if ($file = CUploadedFile::getInstanceByName('logo')) {
			//$this->return_json(1, '请上传头像');
			if (!in_array($file->getExtensionName(), explode(',', IMG_UPLOAD_TYPES))) {
				$this->return_json(1, '图片格式不正确');
			}
			if ($file->getSize() > IMG_UPLOAD_SIZE) {
				$this->return_json(1, '图片超出大小');
			}
			$file_name = md5(uniqid()) . '.' . $file->getExtensionName();
			$file->saveAs(PHOTO_DIR . '/' . $file_name);
			$photoid = $this->model('photo')->createPhoto($file_name);
		}
		
		if ($this->model('user')->addUser($request['username'], md5($request['password']), $request['introrid'], $request['nickname'], (int)$request['sex'], $request['hobby'], $request['birthday'], $photoid)) {
			Yii::app()->cache->delete($request['username']);
			$this->return_json(0, '注册成功');
		}
		$this->return_json(1, '注册失败');
	}
	
	/**
	 * 验证码
	 */
	public function actionSendcode()
	{
		$username = $this->getRequest('username');
		if ($username == '') {
			$this->return_json(1, '手机号码不能为空');
		}
		if ($this->model('user')->checkUserName($username)) {
			$this->return_json(1, '此用户已注册');
		}
		/*
		Yii::import('ext.utils.SmsHelper');
		$sms = SmsHelper::get_instance();
		if ($sms->send($username, $sms->create_code())) {
			$this->return_json(0, '发送成功');
		}
		*/
		
		Yii::import('ext.utils.Ucpaas');
		$options['accountsid'] = Ucpaas::AccountSid;
		$options['token'] = Ucpaas::Token;
		$sms = new Ucpaas($options);
		$msg_code = $sms->create_code();
		$json = $sms->templateSMS(Ucpaas::AppId, $username, Ucpaas::tValiCode, $msg_code);
		if (!empty($json)) {
			$json = json_decode($json, true);
			if ($json['resp']['respCode'] == '000000') {
				//写入缓存 有效期60秒
				Yii::app()->cache->set($username, $msg_code, 300);
				$this->return_json(0, '发送成功');
			}
		}
		$this->return_json(1, '发送失败');
	}
	
	public function actionSendcodepass()
	{
		$username = $this->getRequest('username');
		if ($username == '') {
			$this->return_json(1, '手机号码不能为空');
		}
		if ($this->model('user')->checkUserName($username)) {
			/*
			Yii::import('ext.utils.SmsHelper');
			$sms = SmsHelper::get_instance();
			if ($sms->send($username, $sms->create_code())) {
				$this->return_json(0, '发送成功');
			}
			*/
			Yii::import('ext.utils.Ucpaas');
			$options['accountsid'] = Ucpaas::AccountSid;
			$options['token'] = Ucpaas::Token;
			$sms = new Ucpaas($options);
			$msg_code = $sms->create_code();
			$json = $sms->templateSMS(Ucpaas::AppId, $username, Ucpaas::tValiCode, $msg_code);
			if (!empty($json)) {
				$json = json_decode($json, true);
				if ($json['resp']['respCode'] == '000000') {
					//写入缓存 有效期60秒
					Yii::app()->cache->set($username, $msg_code, 300);
					$this->return_json(0, '发送成功');
				}
			}
			$this->return_json(1, '发送失败');
		} else {
			$this->return_json(1, '用户名不存在');
		}
	}
	
	public function actionValicode()
	{
		$valicode = $this->getRequest('validatecode', '');
		$username = $this->getRequest('username', '');
		if (!$valicode) {
			$this->return_json(1, '验证码不能为空');
		}
		if (Yii::app()->cache->get($username) != $valicode) {
			$this->return_json(1, '验证码不正确');
		}
		$this->return_json(0, '验证通过');
	}
	
	
	/**
	 * 动态发布
	 */
	public function actionAddFeed()
	{
		$request = array();
		$params = array('userid', 'content', 'priority');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['userid']) {
			$this->return_json(1, '用户id不能为空');
		}
		if (!$this->model('user')->getUserById($request['userid'], 'userid')) {
			$this->return_json(1, '用户不存在');
		}
		$titlelogo = '';
		$content = !empty($request['content']) ? $request['content'] : '';
		$item_photo = array();
		
		if ($files = CUploadedFile::getInstancesByName('files')) {
			if (!empty($files)) {
				foreach ($files as $i => $file) {
					if (!in_array($file->getExtensionName(), explode(',', IMG_UPLOAD_TYPES))) {
						$this->return_json(1, '图片格式不正确');
					}
					if ($file->getSize() > IMG_UPLOAD_SIZE) {
						$this->return_json(1, '图片超出大小');
					}
					$file_name = md5(uniqid()) . '.' . $file->getExtensionName();
					if ($file->saveAs(PHOTO_DIR . '/' . $file_name)) {
						$photoid = $this->model('photo')->createPhoto($file_name);
						//第一张图设为封面
						if ($i == 0) {
							$titlelogo = $file_name;
							copy(PHOTO_DIR . '/' . $titlelogo, ITEM_LOGO_DIR . '/' . $titlelogo);
						}
						$item_photo[] = $photoid;
					}
				}
			}
		}
		
		if (!in_array($request['priority'], array(1,2,3))) {
			$request['priority'] = 1;
		}
		if ($this->model('item')->addTrends($titlelogo, $content, $request['userid'], $request['priority']) !== false) {
			$itemid = $this->model('item')->getLastInsertID();
			$this->model('ItemUser')->save($request['userid'], $itemid, 1);
			$item_photo_data = array();
			if (!empty($item_photo)) {
				foreach ($item_photo as $photoid) {
					$item_photo_data[] = array('photoid' => $photoid, 'itemid' => $itemid);
				}
				$this->model('ItemPhoto')->insertMultiple($item_photo_data);
			}
			$this->return_json(0, '发布成功');
		}
		$this->return_json(1, '发布失败');
	}
	
	public function actionAddarticle()
	{
		$request = array();
		$params = array('userid', 'content', 'title', 'priority');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['userid']) {
			$this->return_json(1, '用户id不能为空');
		}
		if (!$this->model('user')->getUserById($request['userid'], 'userid')) {
			$this->return_json(1, '用户不存在');
		}
		$titlelogo = '';
		$content = !empty($request['content']) ? $request['content'] : '';
		$item_photo = array();
		
		$save_files = array();
		if ($files = CUploadedFile::getInstancesByName('files')) {
			if (!empty($files)) {
				foreach ($files as $i => $file) {
					if (!in_array($file->getExtensionName(), explode(',', IMG_UPLOAD_TYPES))) {
						$this->return_json(1, '图片格式不正确');
					}
					if ($file->getSize() > IMG_UPLOAD_SIZE) {
						$this->return_json(1, '图片超出大小');
					}
					$file_name = md5(uniqid()) . '.' . $file->getExtensionName();
					$save_files[$i] = PHOTO_URL . '/mid_' . $file_name;
					if ($file->saveAs(PHOTO_DIR . '/' . $file_name)) {
						$photoid = $this->model('photo')->createPhoto($file_name);
						//第一张图设为封面
						if ($i == 0) {
							$titlelogo = $file_name;
							copy(PHOTO_DIR . '/' . $titlelogo, ITEM_LOGO_DIR . '/' . $titlelogo);
						}
						$item_photo[] = $photoid;
					}
				}
			}
		}
	
		$p = '/GTGTGTGT([0-9]+?)/';
		if (preg_match_all($p, $content, $r) > 0) {
			foreach ($r[1] as $i => $f_key) {
				$r[1][$i] = $save_files[$f_key];
			}
			$content = str_replace($r[0], $r[1], $content);
		}
		
		if (!in_array($request['priority'], array(1,2,3))) {
			$request['priority'] = 1;
		}
		if ($this->model('item')->addArticle($request['title'], $titlelogo, $content, $request['priority']) !== false) {
			$itemid = $this->model('item')->getLastInsertID();
			$this->model('ItemUser')->save($request['userid'], $itemid, 1);
			$item_photo_data = array();
			if (!empty($item_photo)) {
				foreach ($item_photo as $photoid) {
					$item_photo_data[] = array('photoid' => $photoid, 'itemid' => $itemid);
				}
				$this->model('ItemPhoto')->insertMultiple($item_photo_data);
			}
			$this->return_json(0, '发布成功');
		}
		$this->return_json(1, '发布失败');
	}
	
	/**
	 * 忘记密码
	 */
	public function actionForgetpassword()
	{
		$request = array();
		$params = array('username', 'valicode');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['username']) {
			$this->return_json(1, '用户名不能为空');
		}
		if (!$request['valicode']) {
			$this->return_json(1, '验证码不能为空');
		}
		if (Yii::app()->cache->get($request['username']) != $request['valicode']) {
			$this->return_json(1, '验证码不正确');
		}
		if (!$this->model('user')->checkUserName($request['username'])) {
			$this->return_json(1, '用户名不存在');
		}
		if ($this->model('user')->updatePassWord($request['username'], md5('123'))) {
			$this->return_json(0, '成功');
			Yii::app()->cache->delete($request['username']);
		}
		$this->return_json(1, '失败');
	}
	
	/**
	 * 修改密码
	 */
	public function actionModifypassword()
	{
		$request = array();
		$params = array('userid', 'oldpassword', 'newpassword');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['userid']) {
			$this->return_json(1, '用户id不能为空');
		}
		if (!$request['oldpassword']) {
			$this->return_json(1, '老密码不能为空');
		}
		if (!$request['newpassword']) {
			$this->return_json(1, '新密码不能为空');
		}
		if (!$this->model('user')->isExistByUserId($request['userid'], md5($request['oldpassword']))) {
			$this->return_json(1, '请输入正确的原密码');
		}
		if ($this->model('user')->updatePassWordByUserId($request['userid'], md5($request['newpassword']))) {
			$this->return_json(0, '密码修改成功，请重新登录！');
		}
		$this->return_json(1, '密码修改失败');
	}
	
	public function actionResetpassword()
	{
		$request = array();
		$params = array('username', 'password');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['username']) {
			$this->return_json(1, '用户名不能为空');
		}
		if (!$request['password']) {
			$this->return_json(1, '新密码不能为空');
		}
		
		if (!$this->model('user')->checkUserName($request['username'])) {
			$this->return_json(1, '用户不存在');
		}
		if ($this->model('user')->updatePassWordByUserName($request['username'], md5($request['password']))) {
			$this->return_json(0, '密码修改成功，请重新登录！');
		}
		$this->return_json(1, '密码修改失败');
	}
	
	/**
	 * 修改头像
	 */
	public function actionChangeLogo()
	{
		$userid = $this->getRequest('userid');
		if (!$userid) {
			$this->return_json(1, '用户id不能为空');
		}
		if (!$this->model('user')->getUserById($userid, 'userid')) {
			$this->return_json(1, '用户不存在');
		}
		if (!$file = CUploadedFile::getInstanceByName('file')) {
			$this->return_json(1, '请上传头像');
		}
		if (!in_array($file->getExtensionName(), explode(',', IMG_UPLOAD_TYPES))) {
			$this->return_json(1, '图片格式不正确');
		}
		if ($file->getSize() > IMG_UPLOAD_SIZE) {
			$this->return_json(1, '图片超出大小');
		}
		$file_name = md5(uniqid()) . '.' . $file->getExtensionName();
		if ($file->saveAs(PHOTO_DIR . '/' . $file_name)) {
			$photoid = $this->model('photo')->createPhoto($file_name);
			$this->model('user')->firstUpdate($userid, 30);
			$this->model('user')->updateLogoByUserId($userid, $photoid);
			echo json_encode(array(
				'code' => 0,
				'msg' => '修改成功',
				'logopath' => PHOTO_URL . '/' . $file_name
			));die;
		}
		$this->return_json(1, '修改失败');
	}
	
	/**
	 * 昵称等其他信息修改
	 */
	public function actionEditInfo()
	{
		$request = array();
		$params = array('userid', 'fieldname', 'value');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['userid']) {
			$this->return_json(1, '用户id不能为空');
		}
		if (!$request['fieldname']) {
			$this->return_json(1, 'fieldname不能为空');
		}
		if (!$request['value'] && !is_numeric($request['value'])) {
			$this->return_json(1, 'value不能为空');
		}
		if (!$this->model('user')->getUserById($request['userid'], 'userid')) {
			$this->return_json(1, '用户不存在');
		}
		$user = array(
			$request['fieldname'] => $request['value']
		);
		
		if (in_array($request['fieldname'], array('truename', 'nickname', 'sin'))) {
			$this->model('user')->firstUpdate($request['userid'], 30);
		}
		if ($this->model('user')->update($user, 'userid = :userid', array(':userid' => $request['userid'])) !== false) {
			$this->return_json(0, '成功');
		}
		$this->return_json(1, '失败');
	}
	
	/**
	 * 会员&女神信息
	 */
	public function actionInfo()
	{
		$username = $this->getRequest('username');
		$user = $this->model('User')->getUserByUserName($username);
		if (!$user) {
			echo json_encode(array('userinfo' => ''));
			die;
		}
		if ($user['logoid'] > 0) {
			$photo = $this->model('photo')->findByPk($user['logoid']);
			$user['logopath'] = PHOTO_URL . '/' . $photo['midpath'];
		}
		$usermoney = $this->model('UserMoney')->findByPk($user['userid']);
		$user['howmuch'] = $usermoney['howmuch'];
		$sex = array(0 => '保密', 1 => '男', 2 => '女');
		$user['sex'] = $sex[$user['sex']];
		$res['userinfo'] = $user;
		
		if ($user['usertype'] == USER_TYPE_GIRL) {
			$beauty = $this->model('beauty')->findByPk($user['userid']);
			$res['beautyinfo'] = $beauty;
		}
		echo json_encode($res);
		die;
	}
	
	public function actionInfobyid()
	{
		$userid = $this->getRequest('userid');
		$user = $this->model('User')->getUserById($userid);
		if (!$user) {
			echo json_encode(array('userinfo' => ''));
			die;
		}
		if ($user['logoid'] > 0) {
			$photo = $this->model('photo')->findByPk($user['logoid']);
			$user['logopath'] = PHOTO_URL . '/' . $photo['midpath'];
		}
		$usermoney = $this->model('UserMoney')->findByPk($user['userid']);
		$user['howmuch'] = $usermoney['howmuch'];
		$res['userinfo'] = $user;
		
		if ($user['usertype'] == USER_TYPE_GIRL) {
			$beauty = $this->model('beauty')->findByPk($user['userid']);
			$res['beautyinfo'] = $beauty;
		}
		echo json_encode($res);
		die;
	}
	
	/**
	 * 女神列表
	 */
	public function actionWomen()
	{
		$truename = (string) $this->getRequest('truename', '');
		$userid = $this->getRequest('userid', '');
		$list = $this->model('user')->getGirlList($truename);
		if ($list) {
			foreach ($list as $i => $item) {
				if ($item['midpath'] != '') {
					$list[$i]['midpath'] = PHOTO_URL . '/' . $item['midpath'];
					$list[$i]['isfocus'] = $this->model('guanzhu')->isExist($userid, $item['userid']);
				}
				$list[$i]['truename'] = $item['nickname'];	
			}
		}
		echo json_encode(array('userinfos' => $list));
		die;
	}
	
	public function actionHotList()
	{
		$truename = $this->getRequest('truename', '');
		$list = $this->model('user')->getGirlList($truename, true);
		if ($list) {
			foreach ($list as $i => $item) {
				if ($item['midpath'] != '') {
					$list[$i]['midpath'] = PHOTO_URL . '/' . $item['midpath'];
				}
				$list[$i]['truename'] = $item['nickname'];
			}
		}
		echo json_encode(array('userinfos' => $list));
		die;
	}
	
	public function actionAddshipping()
	{
		$request = array();
		$params = array('userid', 'mobile', 'area', 'dizhi', 'zipcode', 'name');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		if (!$request['userid']) {
			$this->return_json(1, '用户id不能为空');
		}
		$request['createtime'] = time();
		if ($this->model('Shipping')->insert($request, true) !== false) {
			$this->return_json(0, '成功');
		}
		$this->return_json(1, '失败');
	}
	
	public function actionGetshipping()
	{
		$userid = $this->getRequest('userid');
		if (!$userid) {
			$this->return_json(1, '用户id不能为空');
		}
		$res = array(
			'code' => '0', 
			'msg' => '成功',
			'info' => array(
				'mobile' => '',
				'area' => '',
				'dizhi' => '',
				'zipcode' => '',
				'name' => ''
			)
		);
		if ($shipping = $this->model('Shipping')->findByPk($userid)) {
			$res['info'] = $shipping;
		}
		echo json_encode($res);die;
	}
	
	/**
	 * 我的来访列表
	 */
	public function actionMyvisitors()
	{
		$userid = $this->getRequest('userid');
		$visits = $this->model('Visitlog')->getList($userid);
		if (!empty($visits)) {
			foreach ($visits as $i => $item) {
				$visits[$i]['visitime'] = date('Y-m-d H:i:s', $item['visitime']);
				$visits[$i]['logopath'] = PHOTO_URL . '/' . $item['midpath'];
			}
		}
		$res = array(
			'code' => '0',
			'msg' => '成功',
			'visitors' => $visits
		);
		echo json_encode($res);die; 
	}
	
	public function actionSupportme()
	{
		$request = array();
		$params = array('pageno', 'pagesize', 'userid', 'itemid');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		!$request['pageno'] && $request['pageno'] = 1;
		!$request['pagesize'] && $request['pagesize'] = 10;
		$list = $this->model('reply')->getListSupportMe($request['userid'], 1, $request['pageno'], $request['pagesize'], 'r.replyerid,sum(r.howmuch) howmuch,u.nickname as truename,p.midpath logopath', $request['itemid']);
		if (!empty($list)) {
			foreach ($list as $i => $item) {
				$list[$i]['logopath'] = !empty($list[$i]['logopath']) ? PHOTO_URL . '/' . $item['logopath'] : '';
			}
		}
		$result['code'] = 0;
		$result['msg'] = '成功';
		$result['supportors'] = $list;
		echo json_encode($result);die;
	}
	
	public function actionMyinvite()
	{
		$request = array();
		$params = array('pageno', 'pagesize', 'username');
		foreach ($params as $item) {
			$request[$item] = $this->getRequest($item);
		}
		!$request['pageno'] && $request['pageno'] = 1;
		!$request['pagesize'] && $request['pagesize'] = 10;
		$list = $this->model('User')->getListByIntrorid($request['username'], $request['pageno'], $request['pagesize'], 'userid,nickname as truename,createtime');
		if (!empty($list)) {
			foreach ($list as $i => $item) {
				$user = $this->model('User')->getUserPhoto($item['userid'], 'p.midpath logopath');
				$list[$i]['logopath'] = !empty($user['logopath']) ? PHOTO_URL . '/' . $user['logopath'] : '';;
				$list[$i]['createtime'] = date('m-d H:i', $item['createtime']);
			}
		}
		$result['code'] = 0;
		$result['msg'] = '成功';
		$result['supportors'] = $list;
		echo json_encode($result);die;
	}
}
